package com.lin.missyou.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.missyou.exception.http.ServerErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.List;

//反序列化工具类
@Component
public class GenericAndJson {


    private static ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper) {
        GenericAndJson.mapper = mapper;
    }


    public static <T> String objectToJson(T o) {
        try {
            return GenericAndJson.mapper.writeValueAsString(o);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServerErrorException(99999);
        }
    }


    public static <T> T jsonToObject(String s, TypeReference<T> typeReference) {
        if (s == null) return null;
        try {
            return GenericAndJson.mapper.readValue(s, typeReference);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
    }

    // List<T> 泛型 T
    // List<S>
//    public static <T> T jsonToList(String s, TypeReference<T> typeReference){
//        if (s == null) return null;
//        try {
//            return GenericAndJson.mapper.readValue(s,typeReference);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new ServerErrorException(9999);
//        }
//    }


//    public static <T> List<T> jsonToList(String s) {
//        if (s == null) return null;
//        try {
//            List<T> t = GenericAndJson.mapper.readValue(s, new TypeReference<List<T>>() {
//            });
//            return t;
//        } catch (JsonProcessingException e) {
//            e.printStackTrace();
//            throw new ServerErrorException(9999);
//
//        }
//    }

}
